﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using YAF.Classes;
using YAF.Core;
using YAF.Types.Interfaces;
using YAF.Types.EventProxies;
using YAF.Providers.Roles;
using System.Web.Security;
using System.IO;

public partial class menu_uc_right_nav_registration : DAO.ESWebUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeUI();
        if (!Page.IsPostBack)
        {
            LoadData();
            int langId;
            bool isAdmin = false;
            Int32.TryParse(Session["language"].ToString(), out langId);
            ddlLanguage.SelectedValue = langId.ToString();
            if (Request.Cookies["texchange"] != null && Request.Cookies["texchange"]["logged"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["logged"]) == "true")
            {
                LoadCompany();
                isAdmin = DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"]) == "admin";
                ESi18nButton2.Enabled = false;
                phForm.Visible = false;
                phCompInfo.Visible = true;
                lblCompanyInfo.Text = DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["name"].ToString());
                pnl_free_registration.Visible = false;
                ph_registered.Visible = isAdmin? false:true;
            }
            else
            {
                phForm.Visible = true;
                //YAF.Pages.login uclog = new YAF.Pages.login();
                //phForm.Controls.Add(uclog);
                phCompInfo.Visible = false;
                pnl_free_registration.Visible = true;
                A1.Visible = false;
                ph_registered.Visible = false;
            }
        }
    }

    private void LoadCompany()
    {
        string id = DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["cid"].ToString());
        ESi18nHyperLink18.NavigateUrl = "~/CompanyDetails.aspx?cid=" + id;
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_CompById(@id,@language_id)", conn))
            {
                int cid = 0;
                Int32.TryParse(id, out cid);
                cmd.Parameters.Add("id", cid);
                cmd.Parameters.Add("@language_id", this.LangId);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    if (dr["fileimage"].ToString() != "")
                    {
                        string path = dr["id"].ToString() + "_" + dr["fileimage"].ToString();
                        if (File.Exists(Server.MapPath("~/images/company/" + path)))
                            img_Logo.ImageUrl = "~/images/company/" + path;
                    }
                }
            }
        }
    }

    private void LoadData()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllLanguages(0, 1000000, 'id', 'asc') WHERE isActive = 'True'", conn))
            {
                SqlDataReader dr = null;
                dr = cmd.ExecuteReader();
                if (dr != null)
                {
                    if (dr.HasRows)
                    {
                        while (dr.Read())
                        {
                            ddlLanguage.Items.Add(new ListItem(dr["short"].ToString() + " - " + dr["language_name"].ToString(), dr["id"].ToString()));
                        }
                    }
                }
                dr.Close();
            }
        }
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
    }

    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["language"] = ddlLanguage.SelectedValue;
        Response.Redirect(Request.Url.ToString());
    }

    protected void ESi18nButton2_Click(object sender, EventArgs e)
    {
        if (UserName.Text != "" && Password.Text != "")
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SP_GetUser", conn))
                {
                    SqlParameter[] pars = new SqlParameter[2];
                    cmd.Parameters.Add(new SqlParameter("username", UserName.Text));
                    cmd.Parameters.Add(new SqlParameter("password", DAO.CodeFactory.CalcMD5String(Password.Text)));
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    SqlDataReader dr = null;
                    dr = cmd.ExecuteReader();
                    if (dr != null)
                    {
                        if (dr.HasRows)
                        {
                            long userid = -1;
                            long cid = -1;
                            if (dr.Read())
                            {
                                string type = dr["userType"].ToString();
                                Int64.TryParse(dr["id"].ToString(), out userid);
                                Int64.TryParse(dr["company_id"].ToString(), out cid);
                                ValidateUserForForum(UserName.Text, dr["orig_pass"].ToString(), type, dr["id"].ToString(), dr["cname"].ToString(), dr["lastLogin"].ToString(), dr["company_id"].ToString());
                                DAO.UserManagement.setUserLogged(cid, true);
                                //HttpCookie cookie = new HttpCookie("userInfo", "true");
                                //cookie["type"] = type;
                                //cookie["logged"] = "true";
                                //cookie["admin_id"] = dr["id"].ToString();
                                //cookie["name"] = dr["Name"].ToString();
                                //cookie["lastlogin"] = dr["lastLogin"].ToString();
                                //cookie["cid"] = dr["company_id"].ToString();
                                //cookie.Value = DateTime.Now.ToString();
                                //cookie.Expires = DateTime.Now.AddDays(999);
                                //cookie.Domain = "transportexchange.org";
                                //cookie.Path = "/";
                                //HttpContext.Current.Response.Cookies.Add(cookie);
                                /*Session["type"] = type;
                                Session["logged"] = "true";
                                Session["admin_id"] = dr["id"];
                                Session["name"] = dr["Name"];
                                Session["lastlogin"] = dr["lastLogin"];
                                Session["cid"] = dr["company_id"];*/
                            }
                            DAO.UsersFactory.UpdateLastLogInTime(userid);
                            Response.Redirect(Request.Url.ToString());
                        }
                        else
                        {
                            Session["message"] = "Invalid username or password";
                            Session["message_type_css"] = "par_message_error";
                            Response.Redirect(Request.Url.ToString());
                        }
                    }
                    if (dr != null && !dr.IsClosed) dr.Close();
                }
            }
        }
        else
        {
            Response.Redirect(Request.Url.ToString());
        }
    }

    private void ValidateUserForForum(string userName, string orig_pass, string type, string id, string name, string lastLogin, string company_id)
    {
        ForumPage currentPage = new ForumPageRegistered();
        YafContext PageContext = currentPage.PageContext;
        bool booResult = PageContext.Get<MembershipProvider>().ValidateUser(UserName.Text.Trim(), orig_pass);

        FormsAuthentication.SetAuthCookie("2;1;Administrator", true);

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, "", "/");
        string strEncTicket = FormsAuthentication.Encrypt(ticket);
        if (Request.Cookies["texchange"] != null)
        {
            HttpCookie c = Request.Cookies["texchange"];
            c.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(c);

        }

        HttpCookie authCookie1 = new HttpCookie(".YAFNET_Authentication", strEncTicket);
        authCookie1.Path = "/";
        HttpContext.Current.Response.Cookies.Add(authCookie1);

        HttpCookie authCookie = new HttpCookie("texchange");
        authCookie["type"] = DAO.GlobalSettings.Encrypt(type);
        authCookie["logged"] = DAO.GlobalSettings.Encrypt("true");
        authCookie["admin_id"] = DAO.GlobalSettings.Encrypt(id);
        authCookie["name"] = DAO.GlobalSettings.Encrypt(name);
        authCookie["lastlogin"] = DAO.GlobalSettings.Encrypt(lastLogin);
        authCookie["cid"] = DAO.GlobalSettings.Encrypt(company_id);
        //cookie.Value = DateTime.Now.ToString();
        authCookie.Expires = DateTime.Now.AddDays(999);
        //authCookie.Domain = "transportexchange.org";
        authCookie.Path = "/";

        HttpContext.Current.Response.Cookies.Add(authCookie);
    }

    private void ValidateUserForForum(string p, string p_2)
    {
        ForumPage currentPage = new ForumPageRegistered();
        YafContext PageContext = currentPage.PageContext;
        bool booResult = PageContext.Get<MembershipProvider>().ValidateUser(UserName.Text.Trim(), Password.Text.Trim());

        FormsAuthentication.SetAuthCookie("2;1;Administrator", true);

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, "", "/");
        string strEncTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie authCookie = new HttpCookie("texchange", strEncTicket);
        authCookie["test"] = "test";
        authCookie.Path = "/";
        HttpContext.Current.Response.Cookies.Add(authCookie);
        // validate userName and password...
        //if (this.Get<MembershipProvider>().ValidateUser(p, p_2))
        //{
        //    e.Authenticated = true;
        //}
        //else if (this.Get<YafBoardSettings>().EnableDisplayName)
        //{
        //    var id = this.Get<IUserDisplayName>().GetId(p);

        //    if (id.HasValue)
        //    {
        //        // get the username associated with this id...
        //        p = UserMembershipHelper.GetUserNameFromID(id.Value);

        //        // validate again...
        //        if (this.Get<MembershipProvider>().ValidateUser(p, p_2))
        //        {
        //            this.Login1.UserName = p;
        //            e.Authenticated = true;
        //        }
        //    }
        //}
    }

    //protected void Login1_LoggedIn(object sender, EventArgs e)
    //{
    //    this.Get<IRaiseEvent>().Raise(new SuccessfulUserLoginEvent(this.PageContext().PageUserID));
    //}
}